package com.ricky.onlineShop.shop.trading.service.impl;

import com.ricky.base.repository.BaseRepository;
import com.ricky.common.exception.TradingException;
import com.ricky.onlineShop.shop.trading.pojo.Trading;
import com.ricky.onlineShop.shop.trading.pojo.TradingOrder;
import com.ricky.onlineShop.shop.trading.pojo.TradingPerformance;
import com.ricky.onlineShop.shop.trading.repository.TradingOrderRepository;
import com.ricky.onlineShop.shop.trading.service.ITradingOrderService;
import com.ricky.onlineShop.shop.trading.service.ITradingPerformanceService;
import com.ricky.onlineShop.shop.trading.service.ITradingService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 网店订单Service业务层处理
 *
 * @author ricky
 * @Date 2024-07-08
 */
@Service
@Slf4j
public class TradingOrderServiceImpl implements ITradingOrderService {
    @Autowired
    private TradingOrderRepository tradingOrderRepository;
    @Autowired
    private ITradingPerformanceService iTradingPerformanceService;
    @Autowired
    private ITradingService iTradingService;
    @Override
    public BaseRepository<TradingOrder, String> getRepository() {
        return tradingOrderRepository;
    }


    @Override
    public int deleteTradingOrderById(@NonNull String id) {
        // 查询删除对象
        TradingOrder tradingOrder = getById(id);
        if (tradingOrder == null) {
            throw new RuntimeException("未找到订单信息信息！");
        }
        String tradingId = tradingOrder.getTradingId();
        Trading trading = iTradingService.getById(tradingId);
        try {
            // 查询订单对应绩效
            List<TradingPerformance> byTradingId = iTradingPerformanceService.findByTradingId(tradingId);
            // 删除订单对应绩效
            for (TradingPerformance tradingPerformance : byTradingId){
                iTradingPerformanceService.delete(tradingPerformance);
            }
            // 删除订单
            deleteById(id);
            // 修改推广状态，以便后续拍下
            trading.setDataStatus("0");
            iTradingService.save(trading);
            return 1;
        }catch (Exception e){
            throw new RuntimeException("删除订单失败！");
        }
    }

    @Override
    public TradingOrder findTradingOrderByTradingId(String id) {
        return tradingOrderRepository.findByTradingId(id);
    }
}
